package cn.edu.lcu.cs.architecture.pipe.ore_tcp;

import javax.swing.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PipedOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * 矿井，源源不断地生产矿石
 */
public class Mine {
    private long amount;

    public void run() {
        try (ServerSocket serverSocket = new ServerSocket(Constants.SOCKET_PORT_MINE);
             Socket client = serverSocket.accept();
             ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream())) {
            while (true) {
                Ore ore = dig();
                System.out.println("挖矿：" + amount++ + "\t" + ore);
                out.writeObject(ore);
                Constants.doze();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 挖矿
     *
     * @return 挖出的矿石
     */
    private Ore dig() {
        // 生成0~5之间的随机浮点，作为矿石的尺寸
        return new Ore(new Random().nextDouble() * 5);
    }

    public static void main(String[] args) {
        new Mine().run();
    }
}
